//CS 564:: PROJECT STAGE 5 - RDBS Catalog
//
// Caela Northey (caela) 905 653 2238
// Colin Laska   (laska) 906 150 7258

#include "catalog.h"
#include "query.h"

/*
 * Inserts a record into the specified relation.
 *
 * Returns:
 * 	OK on success
 * 	an error code otherwise
 */

const Status QU_Insert(const string & relation, 
	const int attrCnt, 
	const attrInfo attrList[])
{

  // NOTE: this implementation assumes that attrCnt, and attrList[]
  // have all of the desired information in them already

  RID rid;
  InsertFileScan*  ifs;
  Status status;
  Record rec;

  // go through the projection list and look up each in the 
  // attr cat to get an AttrDesc structure (for offset, length, etc)
  AttrDesc attrDescArray[attrCnt];
  for (int i = 0; i < attrCnt; i++)
  {
    Status status = attrCat->getInfo(relation,
                                     attrList[i].attrName,
                                     attrDescArray[i]);
      if (status != OK)
      {
          return status;
      }
  }//end for

  int rec_len = 0;
  // Get the total length of a record
  for (int i = 0; i < attrCnt; i++){
    rec_len += attrDescArray[i].attrLen;
  }

  // Create a char array and fill it
  char rec_array[rec_len]; //data for rec
  int offset = 0;
  for (int i = 0; i < attrCnt; i++){
    /* incorrect...
    switch(attrDescArray[i].attrType){
      case INTEGER: 
        int val = atoi((void*)attrList[i].attrValue); break;
        memcpy(rec_array+offset, val, attrDescArray[i].attrLen);
      case FLOAT:
        float val = atof((void*)attrList[i].attrValue); break;
        memcpy(rec_array+offset, val, attrDescArray[i].attrLen);
      case STRING:
        memcpy(rec_array+offset, attrList[i].attrValue, attrDescArray[i].attrLen);
    }//end switch */

    // Memcpy at each offset
    memcpy(rec_array+offset, attrList[i].attrValue, attrDescArray[i].attrLen);
    offset+=attrDescArray[i].attrLen;

    //       VISUAL OF WHAT THE MEMCPY IS TRYING TO DO:
    //  ---------------------------------------------------------
    //  |  ...stuff...  | IMPORTANT DATA THINGS |  ...stuff...  |
    //  ---------------------------------------------------------
    //  ^               ^                       ^
    //  rec_array       offset from attr_rec    This is at offset
    //                                             + attrLen

  }//end for

  // Recall:
  //
  // struct Record {
  //   void* data;
  //   int length;
  // };
  rec.data = rec_array;
  rec.length = rec_len;

  // Begin InsertFileScan
  ifs = new InsertFileScan(relation, status);
  if (status != OK){
    return status;
  }

  //Recall: const Status insertRecord (const Record & rec, RID& outRid)
  status = ifs->insertRecord(rec, rid);
  if (status != OK){
    return status;
  }

  delete ifs;

  return OK;
}

